/**
 * FileName: SeckillProducer
 *
 * @author: 阿张
 * Date:     2021/2/25 8:39
 */
package com.qx.mq;

import com.alibaba.fastjson.JSON;
import com.qx.pojo.SeckillCommodity;
import com.qx.service.SeckillCommodityService;
import com.qx.service.SpikeService;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Component
public class SeckillProducer {

    @Resource
    private SpikeService spikeService;

    @Resource
    private SeckillCommodityService seckillCommodityService;

    /**生产者组名*/
    @Value("${suning.rocketmq.producerGroup}")
    private String producerGroup;

    /**NameServer*/
    @Value("${suning.rocketmq.namesrvaddr}")
    private String namesrvAddr;

    @PostConstruct
    public void producer(){
        DefaultMQProducer producer = new DefaultMQProducer(producerGroup);
        producer.setNamesrvAddr(namesrvAddr);
        try {
            producer.start();
            List<SeckillCommodity> list = seckillCommodityService.list();
            String jsonStr = JSON.toJSONString(list);
            System.out.println("发送消息："+jsonStr);
            Message message = new Message("user-topic","user-tag",jsonStr.getBytes(RemotingHelper.DEFAULT_CHARSET));
            SendResult result = producer.send(message);
            System.err.println("发送响应:MsgID"+result.getMsgId()+",发送状态："+result.getSendStatus());
        } catch (MQClientException | UnsupportedEncodingException | RemotingException | MQBrokerException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            producer.shutdown();
        }
    }
}
